﻿/**********************************************
 * 功能名称：原材料的领用及盘存管理
编写人：  杨莹
建立时间： 杨 2008年11月8日
说明：
加载页面时，根据当前用户ID查询出责任部门，列表显示其作业中心列表。
作业中心列表中选择后，列表出作业中心中间体；
选择作业中心中间体，列表当前中间体的材料列表。
用户可编辑“盘存”“领用”两栏信息并提交保存，其他为只读。
 **************************************************************/

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Hisun.Models;
using Hisun.Controllers;
using System.Collections.Generic;




namespace Hisun.View.Meterial
{
    public partial class DirectMeterial : AbcPageBase
    {
        HisunDBDataContext db = new HisunDBDataContext();

        public string alter;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                var CurrentUserCenterId = (from a in db.TAbc_JS_Users where a.操作员ID == Session[ServerVars.sysSessionUserName].ToString() select new { a.责任部门ID }).Single();
                dropCostCenterSelect.Items.Clear();
                FillData2DropDownList(Convert.ToInt32(CurrentUserCenterId.责任部门ID));
               // BindData();


            }
        }





        //查询当前操作员对应的作业中心列表
        private void FillData2DropDownList(int CenterID)
        {
            ChildCenterList myCenter = new ChildCenterList(CenterID);

            var myCenterFilters = myCenter.CostCenterlist.Where(p => new string[] { "A","BF", "BG", "BZ" }.Contains(p.类型) && p.停用 == false);


            foreach (var MylistItem in myCenterFilters)
            {

                ListItem InsertItem = new ListItem(MylistItem.作业中心名称, MylistItem.作业中心ID.ToString());
                dropCostCenterSelect.Items.Add(InsertItem);
            }


        }


        //保存月末盘存量
        protected void Button_Save_Click(object sender, EventArgs e)
        {


            string CenterId = HiddenField_CenterId.Value.ToString();

            var IsLocked = (from a in db.TABC_JC_MeterialResumption
                            where a.作业中心ID == Convert.ToInt32(CenterId)
                            && a.会计期间ID == Application["accountPeriod"].ToString()
                            && a.锁定 == true
                            select a.作业中心ID).Count();
            if (IsLocked > 0)
            {
                alter = "<script>alert('当前作业中心已锁定');</script>";
                return;

            }


            string PIPId = HiddenField_PIPId.Value.ToString();

            if (!Page.IsValid)
            {
                alter = "<script>alert('非法数据输入,请修改');</script>";
                return;
            }


            try
            {
                for (int i = 0; i < GridView_Meterial.Rows.Count; i++)
                {
                    int myid = Convert.ToInt32(GridView_Meterial.DataKeys[i]["ID"].ToString());
                    string mynum = ((TextBox)GridView_Meterial.Rows[i].Cells[7].FindControl("TextBox_FinalValue")).Text;

                    decimal MyMount = Convert.ToDecimal(mynum);

                    if (myid == 0)
                    {
                        if (MyMount > 0)
                        {
                            TABC_JC_MeterialResumption myNewRow = new TABC_JC_MeterialResumption();
                            myNewRow.公司ID = "hisun";
                            myNewRow.账套ID = "001";
                            myNewRow.会计期间ID = Application[ServerVars.sysApplcationAccountPeriod].ToString();
                            myNewRow.作业中心ID = Convert.ToInt32(CenterId);
                            myNewRow.中间体ID = PIPId;
                            myNewRow.材料ID = GridView_Meterial.Rows[i].Cells[1].Text;
                            myNewRow.计量单位 = GridView_Meterial.Rows[i].Cells[3].Text;
                            myNewRow.期初数量 = 0;
                            myNewRow.期初金额 = 0;
                            myNewRow.领用数量 = 0;
                            myNewRow.领用金额 = 0;
                            myNewRow.期末数量 = MyMount;
                            myNewRow.产品领料 = false;

                            db.TABC_JC_MeterialResumption.InsertOnSubmit(myNewRow);
                            db.SubmitChanges();
                        }

                    }
                    else
                    {
                        var myrow = (from a in db.TABC_JC_MeterialResumption
                                    where a.ID == myid
                                    select a).Single();

                        if (MyMount > 0)
                        {
                            myrow.期末数量 = MyMount;
                        }
                        else
                        {
                            myrow.期末数量 = 0;
                        }

                        db.SubmitChanges();

                    }
                         

                    
                    
                }

                alter = "<script>alert('更新数据成功');</script>";
                BindData();
            }
            catch
            {
               alter = "<script>alert('更新数据失败');</script>";
            }
        }



        //绑定数据来源
        protected void Button_Query_Click(object sender, EventArgs e)
        {
            BindData();
        }



        private void BindData()
        {

            HiddenField_CenterId.Value =  dropCostCenterSelect.SelectedValue;
            HiddenField_PIPId.Value = DropDownListSelectProductInProccess.SelectedValue;

            string CenterId = HiddenField_CenterId.Value.ToString();
            string PIPId = HiddenField_PIPId.Value.ToString();

            //建立视图，查询出前作业中心的，中间产品材料的期初、领用、消耗、盘存信息。
            var MyMeterial_list = (from a in db.VABC_JS_ProductAndMeterial
                                  where (from b in db.TABC_JC_MeterialResumption
                                         where b.作业中心ID == Convert.ToInt32(CenterId)
                                   && b.中间体ID == PIPId
                                   select b.材料ID).Contains(a.材料ID)
                                      select new
                                      {a.材料ID}).Distinct();



            var MyMeterialQuery = from a in
                                      (from x in MyMeterial_list
                                       join z in
                                           (from h in db.VABC_JS_ProductAndMeterial
                                            group h by h.材料ID into m
                                            select new
                                            {
                                                材料ID = m.Key,
                                                材料名称 = m.Max(h => h.材料名称),
                                                计量单位 = m.Max(h => h.计量单位)
                                            }) on x.材料ID equals z.材料ID
                                       select new 
                                       {
                                           x.材料ID,
                                           z.材料名称,
                                           z.计量单位
                                       
                                       
                                       })
                                  join b in
                                      (from c in db.TABC_JC_MeterialResumption
                                       where c.作业中心ID == Convert.ToInt32(CenterId)
                                         && c.中间体ID == PIPId
                                         && c.会计期间ID == Application["accountPeriod"].ToString()
                                       select c)
                                   on a.材料ID equals b.材料ID

                                  into mytemps
                                  orderby a.材料ID
                                  from mytemp in mytemps.DefaultIfEmpty()
                                  select new
                                  {
                                      会计期间 = (mytemp.会计期间ID == null ? "" : mytemp.会计期间ID),
                                      材料ID = a.材料ID,
                                      计量单位 = a.计量单位,
                                      期初数量 = (mytemp.期初数量 == null ? 0 : mytemp.期初数量),
                                      领用数量 = (mytemp.领用数量 == null ? 0 : mytemp.领用数量),
                                      本期耗用 = (mytemp.本期耗用 == null ? 0 : mytemp.本期耗用),
                                      期末数量 = (mytemp.期末数量 == null ? 0 : mytemp.期末数量),
                                      材料名称 = (mytemp.ID == null ? "(?)" + a.材料名称 : a.材料名称),
                                      作业中心ID = (mytemp.作业中心ID == null ? 0 : mytemp.作业中心ID),
                                      ID = (mytemp.ID == null ? 0 : mytemp.ID)
                                  };


                                  



            GridView_Meterial.DataSource = MyMeterialQuery;
            GridView_Meterial.DataBind();

            if (GridView_Meterial.Rows.Count == 0)
            { Button_Save_1.Visible = false; }
            else
            { Button_Save_1.Visible = true;  }


        }

        //增加原材料记录
        protected void Button_AddMeterial_Click(object sender, EventArgs e)
        {
            string MyCenterId = dropCostCenterSelect.SelectedValue;
            string MyPIPId = DropDownListSelectProductInProccess.SelectedValue;
            Response.Redirect("InsertDirectMeterial.aspx?centerid=" + MyCenterId + "&PIPid=" + MyPIPId);
        }
    }
}
